package com.leetcode;

import java.util.Iterator;
import java.util.List;

/**
 * 341. 扁平化嵌套列表迭代器
 * 官方解法不符合迭代器的理念，迭代器不应该对item的值做直接存储，
 * 而应提供访问途径：
 *      1.迭代有条件终止(如键值查找)时初始化方法的全局开销非必要.
 *      2.初始化迭代器后，迭代过程中无法处理List中某NestedInteger值(int值)改变的场景
 *
 * @author fy
 * @date 2022/4/13 11:09
 */
public class Solution341_2 {

    public interface NestedInteger {

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger();

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return empty list if this NestedInteger holds a single integer
        public List<NestedInteger> getList();
    }

    public class NestedIterator implements Iterator<Integer> {
        private final List<NestedInteger> nestedList;
        private final int size;
        private int i = 0;
        private NestedIterator iterator = null;

        public NestedIterator(List<NestedInteger> nestedList) {
            this.nestedList = nestedList;
            size = nestedList.size();
        }

        @Override
        public Integer next() {
            NestedInteger curr = nestedList.get(i);
            if (curr.isInteger()) {
                i++;
                return curr.getInteger();
            } else {
                return iterator.next();
            }
        }

        @Override
        public boolean hasNext() {
            while (i < size) {
                NestedInteger curr = nestedList.get(i);
                if (curr.isInteger()) {
                    return true;
                } else {
                    if (iterator == null) {
                        // 如果是列表嵌套生成一个NestedIterator
                        iterator = new NestedIterator(curr.getList());
                    }

                    if (iterator.hasNext()) {
                        return true;
                    } else {
                        iterator = null;
                        i++;
                    }
                }
            }

            return false;
        }
    }

}
